package com.kkd.kkdapp.activity;

import org.json.JSONException;
import org.json.JSONObject;

import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;
import com.kkd.kkdapp.R;
import com.kkd.kkdapp.base.BaseActivity;
import com.kkd.kkdapp.http.entity.BondTransferParData;
import com.kkd.kkdapp.http.manager.HttpCallBack;
import com.kkd.kkdapp.http.manager.KkdHttpMagager;
import com.kkd.kkdapp.listener.OnSingleClickListener;
import com.kkd.kkdapp.particle2.ParticleSystem;
import com.kkd.kkdapp.utils.DialogUtils;
import com.kkd.kkdapp.utils.PreferenceUtils;
import com.kkd.kkdapp.utils.SystemUtils;

import android.app.Dialog;
import android.content.Intent;
import android.graphics.Color;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.text.TextUtils;
import android.view.KeyEvent;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;

/*****
 * 
 * @Name 债权购买成功
 * 
 * @author mty
 * 
 */
public class CreditorIsRightsTenderAffirmSuccessActivity extends BaseActivity
		implements OnClickListener {

	public static final int CLOSE_CODE = 101; // 关闭
	public static final int CONTINUE_TO_BUY = 102; // 继续购买
	private static final int CAMPAIGN_SUCCESS = 1;
	public static final int TOENJOY_CLOSE_RESULT_CODE = 20003;

	private RelativeLayout result_title_img; // 完成
	private TextView bidname; // 产品名称
	private BondTransferParData data;
	private TextView method_tv; // 还款方式
	private TextView repaymentDate_tv; // 下一个还款日
	private TextView buyamount_tv; // 购买金额TextView
	private TextView buynumber_tv; // 购买份数
	private TextView expected_return_tv1, expected_return_tv2,
			expected_return_tv3, expected_return_tv4; // 剩余期限
	private TextView repayment_tv;
	private TextView see_bt; // 查看我的债权
	private Button examine; // 继续购买
	private TextView startInterest_tv; // 开始计息
	private String buyAmount; // 购买金额
	private String poiId;
	private int productType;
	private Dialog dialog_finishShoutou;
	private String url; // 摇奖机会跳转Url
	private RelativeLayout draw_lottery_rl; // 摇奖机会
	private LinearLayout main_layout;

	private Handler mHandler = new Handler() {
		public void handleMessage(android.os.Message msg) {
			switch (msg.what) {
			case CAMPAIGN_SUCCESS: // 投标成功活动请求成功
				try {
					String customerIdAndToken = PreferenceUtils
							.getInstance()
							.getcustomerId(
									CreditorIsRightsTenderAffirmSuccessActivity.this);
					final String[] cat = customerIdAndToken.split("&");
					Object responseBody = msg.obj;
					String reponString = responseBody.toString();
					final JSONObject data = new JSONObject(reponString);
					boolean popUp = data.optBoolean("popUp");
					final int isLuckyFlag = data.optInt("isLuckyFlag");
					String mis_succ_image = data.optString("mis_succ_image");// 是否首投开启特权
					if (isLuckyFlag == 1) {
						String luckyUrl = data.getString("luckyUrl");
						url = luckyUrl + "&customerId=" + cat[1] + "&token="
								+ cat[0] + "&channel=Android";
						draw_lottery_rl.setVisibility(View.VISIBLE);
						main_layout.setBackgroundColor(Color
								.parseColor("#f0eef3"));
						mHandler.postDelayed(new Runnable() {

							@Override
							public void run() {
								// 设置粒子扩散效果
								ParticleSystem particleSystem = new ParticleSystem(
										CreditorIsRightsTenderAffirmSuccessActivity.this,
										100, R.drawable.sign, 800);
								particleSystem
										.setContext(CreditorIsRightsTenderAffirmSuccessActivity.this);
								particleSystem.setSpeedRange(0.025f, 0.045f)
										.oneShot(findViewById(R.id.shake_icon),
												50);
							}
						}, 1000);
					}
					if (TextUtils.isEmpty(mis_succ_image)) {// 说明不是首投，走以前的逻辑
						if (popUp) {
							// 签到完成状态，0未完成，1完成；
							int signInStatus = data.getInt("signInStatus");
							// 签到获取快乐币个数
							int signInCionSum = data.getInt("signInCionSum");
							// 签到优惠券金额
							long signIncouponAmount = data
									.getLong("signIncouponAmount");
							// 连续签到天数
							int days = data.getInt("days");
							// 分享邀请好友获得快乐币个数
							int inviteCionSum = data.getInt("inviteCionSum");
							// 0未完成，1完成；
							int inviteStatus = data.getInt("inviteStatus");
							// 投资完成状态，0未完成，1完成；
							int poiStatus = data.getInt("poiStatus");
							// 投资奖励快乐币个数
							int poiCionSum = data.getInt("poiCionSum");
							// 投资任务未完成提示最高奖励快乐币个数
							int poiMoreCionSum = data.getInt("poiMoreCionSum");
							// 邀请好友攻略Url
							String inviteStrategyUrl = data
									.getString("inviteStrategyUrl");
							// 快乐币任务全部完成获取快乐币总数
							int doubleAllSum = data.getInt("doubleAllSum");
							// 完成快乐币任务排名
							int customerSeat = data.getInt("customerSeat");
							// 完成任务获得快乐币个数
							int doubleSum = data.getInt("doubleSum");
							// 完成快乐币任务翻倍的倍率
							String doubleRate = data.getString("doubleRate");
							// 翻倍获取快乐币个数
							int doubleMisSum = data.getInt("doubleMisSum");
							// 快乐币任务url
							String coinMisUrl = data.getString("coinMisUrl");
							// 是否可以补签 0：不可以，1：可以
							int isRepairSigninStatus = data
									.getInt("isRepairSigninStatus");
							happyCoinCompleteProgressDialog(signInStatus,
									signInCionSum, signIncouponAmount, days, 3,
									inviteCionSum, inviteStatus, poiStatus,
									poiCionSum, poiMoreCionSum,
									inviteStrategyUrl, doubleAllSum,
									customerSeat, doubleSum, doubleRate,
									doubleMisSum, coinMisUrl,
									isRepairSigninStatus);
						}
					} else {
						if (dialog_finishShoutou != null) {
							dialog_finishShoutou.cancel();
							dialog_finishShoutou = null;
						}
						final String moneyTreeUrl = data
								.optString("moneyTreeUrl");
						dialog_finishShoutou = DialogUtils
								.finishXinshouShoutouDialog(
										CreditorIsRightsTenderAffirmSuccessActivity.this,
										mis_succ_image,
										new OnSingleClickListener() {

											@Override
											public void onSingleClick(View v) {
												if (dialog_finishShoutou != null) {
													dialog_finishShoutou
															.cancel();
												}
												if (!TextUtils
														.isEmpty(moneyTreeUrl)) {
													Intent intent = new Intent(
															CreditorIsRightsTenderAffirmSuccessActivity.this,
															KKDWebActivity.class);
													intent.putExtra(
															"url",
															moneyTreeUrl
																	+ "&customerId="
																	+ cat[1]
																	+ "&token="
																	+ cat[0]
																	+ "&channel=Android");
													startActivity(intent);
												}
											}
										});
						dialog_finishShoutou.show();
					}
				} catch (JSONException e) {
					e.printStackTrace();
				}
				break;
			}
		};
	};

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_creditor_is_rights_tender_affirm_success);
		initView();
		setListener();
		getMessage();
		tenderAffirmCampaign();
	}

	/****
	 * 初始化控件
	 */
	public void initView() {
		result_title_img = (RelativeLayout) this
				.findViewById(R.id.result_title_img);
		bidname = (TextView) this.findViewById(R.id.bidname);
		startInterest_tv = (TextView) this.findViewById(R.id.startInterest_tv);
		repaymentDate_tv = (TextView) this.findViewById(R.id.repaymentDate_tv);
		buyamount_tv = (TextView) this.findViewById(R.id.buyamount_tv);
		buynumber_tv = (TextView) this.findViewById(R.id.buynumber_tv);
		expected_return_tv1 = (TextView) this
				.findViewById(R.id.expected_return_tv1);
		expected_return_tv2 = (TextView) this
				.findViewById(R.id.expected_return_tv2);
		expected_return_tv3 = (TextView) this
				.findViewById(R.id.expected_return_tv3);
		expected_return_tv4 = (TextView) this
				.findViewById(R.id.expected_return_tv4);
		repayment_tv = (TextView) this.findViewById(R.id.repayment_tv);
		see_bt = (TextView) this.findViewById(R.id.see_bt);
		examine = (Button) this.findViewById(R.id.examine);
		method_tv = (TextView) this.findViewById(R.id.method_tv);
		main_layout = (LinearLayout) this.findViewById(R.id.main_layout);
		main_layout.setBackgroundColor(Color.parseColor("#FFFFFF"));
		draw_lottery_rl = (RelativeLayout) this
				.findViewById(R.id.draw_lottery_rl);
	}

	/****
	 * 注册监听事件
	 */
	public void setListener() {
		result_title_img.setOnClickListener(this);
		see_bt.setOnClickListener(this);
		examine.setOnClickListener(this);
		draw_lottery_rl.setOnClickListener(this);
	}

	/**
	 * 获取上个界面传值
	 */
	public void getMessage() {
		Intent intent = this.getIntent();
		String json = intent.getStringExtra("json");
		Gson gson = new Gson();
		data = gson.fromJson(json, new TypeToken<BondTransferParData>() {
		}.getType());
		String repaymentType = intent.getStringExtra("repaymentType");
		String nextCollectDate = intent.getStringExtra("nextCollectDate");
		buyAmount = intent.getStringExtra("buyAmount");
		String buynumber = intent.getStringExtra("buynumber");
		String estimate = intent.getStringExtra("estimate");
		String startInterest = intent.getStringExtra("startInterest");
		poiId = intent.getStringExtra("poiId");
		productType = intent.getIntExtra("productType", -1);

		// 产品名称
		bidname.setText(data.getTitle());
		// 购买金额
		buyamount_tv.setText(buyAmount);
		// 购买份数
		buynumber_tv.setText(buynumber);
		// 剩余期限
		int leftTermMont = data.getLeftTermMonthDesc();
		int leftTermDayDesc = data.getLeftTermDayDesc();
		if (leftTermMont != 0 && leftTermDayDesc != 0) {
			expected_return_tv1.setText("" + leftTermMont);
			expected_return_tv2.setText("个月");
			expected_return_tv3.setText("" + leftTermDayDesc);
			expected_return_tv4.setText("天");
		} else if (leftTermMont == 0) {
			expected_return_tv1.setText("" + leftTermDayDesc);
			expected_return_tv2.setText("天");
			expected_return_tv3.setText("");
			expected_return_tv4.setText("");
		} else if (leftTermDayDesc == 0) {
			expected_return_tv1.setText("" + leftTermMont);
			expected_return_tv2.setText("个月");
			expected_return_tv3.setText("");
			expected_return_tv4.setText("");
		} else if (leftTermMont == 0 && leftTermDayDesc == 0) {
			expected_return_tv1.setText("" + leftTermMont);
			expected_return_tv2.setText("个月");
			expected_return_tv3.setText("" + leftTermDayDesc);
			expected_return_tv4.setText("天");
		}
		// 预计赚得收益
		repayment_tv.setText(estimate + "元");
		// 还款方式
		method_tv.setText(repaymentType);
		// 下一个还款日
		repaymentDate_tv.setText(nextCollectDate);
		// 开始计息
		startInterest_tv.setText(startInterest);
	}

	@Override
	public void onClick(View v) {
		Intent intent;
		switch (v.getId()) {
		case R.id.result_title_img: // 完成
			setResult(CLOSE_CODE);
			finish();
			break;
		case R.id.see_bt: // 查看我的债权
			intent = new Intent(this, MyRegularDebtActivity.class);
			startActivity(intent);
			setResult(CLOSE_CODE);
			finish();
			break;
		case R.id.examine: // 继续购买
			setResult(CONTINUE_TO_BUY);
			finish();
			break;
		case R.id.draw_lottery_rl: // 摇奖机会
			if (!TextUtils.isEmpty(url)) {
				SystemUtils.onEvent("Regular_Result_GotoLotteryn", 1);
				intent = new Intent(
						CreditorIsRightsTenderAffirmSuccessActivity.this,
						KKDWebActivity.class);
				intent.putExtra("url", url);
				startActivity(intent);
				setResult(TOENJOY_CLOSE_RESULT_CODE);
				finish();
			}
			break;
		}
	}

	// 投标成功活动
	public void tenderAffirmCampaign() {
		String customerIdAndToken = PreferenceUtils.getInstance()
				.getcustomerId(this);
		final String[] cat = customerIdAndToken.split("&");
		KkdHttpMagager.getInstance().tenderAffirmCampaign(poiId,
				(long) (Double.parseDouble(buyAmount) * 100), productType,
				new HttpCallBack() {

					@Override
					public void onSuccess(int statusCode, Object responseBody) {
						Message msg = new Message();
						msg.what = CAMPAIGN_SUCCESS;
						msg.obj = responseBody;
						mHandler.sendMessage(msg);
					}

					@Override
					public void onFailure(int statusCode, String desc) {

					}
				}, String.class);
	}

	@Override
	public boolean onKeyDown(int keyCode, KeyEvent event) {
		if (keyCode == KeyEvent.KEYCODE_BACK) {
			setResult(CLOSE_CODE);
			finish();
			return true;
		}
		return super.onKeyDown(keyCode, event);
	}

	@Override
	protected void onDestroy() {
		super.onDestroy();
		if (dialog_finishShoutou != null) {
			dialog_finishShoutou.cancel();
			dialog_finishShoutou = null;
		}
	}
}
